# 分工：
#     肖颖杰：单词的删除/修改/查询（独立）、搜索单词（合作）、单词测试（合作）
#     刘世鑫：搜索单词（合作）、单词测试（合作）、绘制雷达图（独立）
#     何汇洋：添加单词（独立）、UI设计、系统整合


import json
import time
import matplotlib.pyplot as plt
import numpy as np
import tkinter as tk
from tkinter import ttk, messagebox, simpledialog
import random

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# 单词测试数量
words_num = 20

class WordApp:
    def __init__(self, master):
        self.master = master
        self.master.title("背单词软件")
        self.words = {}  # 存储单词和释义
        self.load_words()  # 加载单词

        # 设置窗口大小
        self.master.geometry("250x350")

        # 创建单词和释义输入框
        self.word_label = ttk.Label(master, text="单词:")
        self.word_label.grid(row=0, column=0, padx=10, pady=10, sticky="e")
        self.word_entry = ttk.Entry(master)
        self.word_entry.grid(row=0, column=1, padx=10, pady=10)

        self.meanings_label = ttk.Label(master, text="释义:")
        self.meanings_label.grid(row=1, column=0, padx=10, pady=10, sticky="e")
        self.meanings_entry = ttk.Entry(master)
        self.meanings_entry.grid(row=1, column=1, padx=10, pady=10)

        # 创建按钮（放在最后）
        self.add_button = ttk.Button(master, text="添加单词", command=self.add_word_from_entry)
        self.add_button.grid(row=2, column=1, padx=10, pady=10)

        self.view_all_button = ttk.Button(master, text="查看单词", command=self.view_all_words)
        self.view_all_button.grid(row=3, column=1, padx=10, pady=10)

        self.search_button = ttk.Button(master, text="搜索单词", command=self.search_words)
        self.search_button.grid(row=4, column=1, padx=10, pady=10)

        self.test_button = ttk.Button(master, text="单词测试", command=self.word_test)
        self.test_button.grid(row=5, column=1, padx=10, pady=10)

        self.radar_button = ttk.Button(master, text="生成雷达图", command=self.generate_radar_chart)
        self.radar_button.grid(row=6, column=1, padx=10, pady=10)

    def generate_radar_chart(self):
        # 读取用户信息
        user_data = self.read_user_data()

        # 生成雷达图
        self.plot_radar_chart(user_data)

    def read_user_data(self):
        try:
            with open('user.txt', 'r') as f:
                user_data = json.load(f)
                return user_data
        except FileNotFoundError:
            messagebox.showinfo("错误", "找不到用户信息文件 'user.txt'！")

    def plot_radar_chart(self, user_data):
        attributes = ['accuracy', 'elapsed_time', 'status']

        # 创建雷达图
        fig, ax = plt.subplots(subplot_kw=dict(polar=True))
        angles = np.linspace(0, 2 * np.pi, len(attributes), endpoint=False)

        for username, data in user_data.items():
            values = [float(data[attr].rstrip('%')) if attr == 'accuracy' else data[attr] for attr in attributes]
            values += values[:0]  # 闭合雷达图

            # 绘制雷达图
            ax.plot(angles, values, label=username)
            ax.fill(angles, values, alpha=0.25)

        # 设置雷达图的属性
        ax.set_thetagrids(angles * 180 / np.pi, attributes)
        ax.set_title("用户雷达图")
        ax.legend(loc='upper right', bbox_to_anchor=(0.1, 0.1))

        # 创建新的Tkinter窗口
        new_window = tk.Toplevel(self.master)
        new_window.title("雷达图")

        # 在新的Tkinter窗口中显示雷达图
        radar_canvas = FigureCanvasTkAgg(fig, master=new_window)
        radar_canvas.draw()
        radar_canvas.get_tk_widget().pack()

        plt.show()

    def search_words(self):
        search_page = SearchWordsPage(self.master, self.words)
        search_page.mainloop()

    def load_words(self):
        try:
            with open('words.txt', 'r') as f:
                for line in f:
                    line = line.strip()
                    if not line:
                        continue

                    try:
                        word, meanings = line.split(' ', 1)
                        self.words[word] = meanings.split(',')
                    except ValueError:
                        print(f"Error processing line: {line}")
        except FileNotFoundError:
            pass  # 文件不存在时不做任何事情

    def save_words_to_file(self):
        with open('words.txt', 'w') as f:
            for word, meanings in self.words.items():
                f.write(f"{word} {' '.join(meanings)}\n")

    def add_word(self, word, meanings):
        print(f"word={word},meanings={meanings}")
        if word == '' or meanings == '':
            messagebox.showinfo("错误", "非法输入！单词或注释不能为空！")
            return
        if word in self.words:
            messagebox.showinfo("错误", "单词已存在！")
            return

        self.words[word] = meanings.split(',')

        # 排序并写入文件
        sorted_words = sorted(self.words.items())
        with open('words.txt', 'w') as f:
            for word, meanings in sorted_words:
                f.write(f"{word} {' '.join(meanings)}\n")

        messagebox.showinfo("成功", "单词添加成功！")
        self.word_entry.delete(0, 'end')  # 清空单词输入框
        self.meanings_entry.delete(0, 'end')  # 清空释义输入框

    def add_word_from_entry(self):
        word = self.word_entry.get()
        meanings = self.meanings_entry.get()
        self.add_word(word, meanings)

    def view_all_words(self):
        view_words_page = ViewWordsPage(self.master, self.words, self)
        view_words_page.mainloop()

    def word_test(self):00
        # 获取20个随机单词
        test_words = random.sample(list(self.words.keys()), words_num)

        # 创建测试窗口
        test_window = WordTestWindow(self.master, self.words, test_words)
        test_window.mainloop()


class WordTestWindow(tk.Toplevel):
    def __init__(self, master, words, test_words):
        super().__init__(master)
        self.title("单词测试")

        # 新增获取用户名的逻辑
        self.username = self.get_username()

        self.words = words
        self.test_words = test_words
        self.answers = {}  # 保存用户的答案

        self.current_word_index = 0

        self.create_widgets()

        self.accuracy = 0  # 正确率

        self.status = "不及格"  # 答题状况

        self.start_time = time.time()  # 记录开始时间
        self.elapsed_time = 0  # 记录耗时

    def get_username(self):
        # 弹窗提示输入用户名
        username = simpledialog.askstring("输入用户名", "请输入您的用户名:")
        return username

    def create_widgets(self):
        self.word_label = ttk.Label(self, text=f"单词：{self.get_current_word()}")
        self.word_label.grid(row=0, column=0, padx=10, pady=10, sticky="e")

        self.answer_label_text = "中文："
        self.answer_label = ttk.Label(self, text=f"{self.answer_label_text}")
        self.answer_label.grid(row=1, column=0, padx=10, pady=10, sticky="e")

        self.answer_entry = ttk.Entry(self)
        self.answer_entry.grid(row=1, column=1, padx=10, pady=10)

        self.submit_button = ttk.Button(self, text="提交", command=self.submit_answer)
        self.submit_button.grid(row=2, column=1, padx=10, pady=10)

    def submit_answer(self):
        answer = self.answer_entry.get()
        correct_answer = self.get_correct_answer()

        # 保存用户的答案
        self.answers[self.get_current_word()] = {
            'user_answer': answer,
            'correct_answer': correct_answer
        }

        # 判断用户输入的答案是否和正确答案有交集
        user_answers = set(answer.split('，'))
        correct_answers = set(correct_answer.split('，'))

        if not user_answers.intersection(correct_answers):
            messagebox.showinfo("错误", "回答错误！正确答案是：" + correct_answer)

        # 切换到下一个单词或显示测试结果
        if self.current_word_index < len(self.test_words) - 1:
            self.current_word_index += 1
            self.show_next_word()
        else:
            # 显示测试结果
            self.show_test_results()

            # 保存用户答题情况到文件
            self.save_user_result()

    def save_user_result(self):

        # 将用户的答题情况保存到文件
        result_filename = 'user.txt'
        user_results = {}
        try:
            with open(result_filename, 'r') as f:
                if f.read().strip():  # 检查文件是否为空
                    f.seek(0)  # 如果文件不为空，将文件指针移回文件开头
                    user_results = json.load(f)
        except FileNotFoundError:
            pass

        # 添加或更新用户的答题情况
        user_results[self.username] = {
            'accuracy': f"{self.accuracy:.2f}%",
            'elapsed_time': self.elapsed_time,
            'status': self.status
        }

        with open(result_filename, 'w') as f:
            json.dump(user_results, f, ensure_ascii=False, indent=2)

    def show_next_word(self):
        self.word_label.config(text=f"单词：{self.get_current_word()}")
        self.answer_label_text = "中文："
        self.answer_label.config(text=f"{self.answer_label_text}")
        self.answer_entry.delete(0, 'end')

    def get_current_word(self):
        return self.test_words[self.current_word_index]

    def get_correct_answer(self):
        word = self.get_current_word()
        meanings = self.words[word]
        return ', '.join(meanings)

    def show_test_results(self):
        # 计算用户的正确率
        total_questions = len(self.test_words)
        correct_answers = sum(1 for word in self.test_words if
                              set(self.answers[word]['user_answer'].split('，')).intersection(
                                  set(self.answers[word]['correct_answer'].split('，'))))
        self.accuracy = (correct_answers / total_questions) * 100

        if self.accuracy == 100:
            self.status = "满分"
        elif self.accuracy >= 90:
            self.status = "优秀"
        elif self.accuracy >= 80:
            self.status = "良好"
        elif self.accuracy >= 60:
            self.status = "及格"

        # 计算答题时间
        end_time = time.time()
        self.elapsed_time = end_time - self.start_time

        result_text = f"测试完成\n正确率：{self.accuracy:.2f}%\n耗时：{self.elapsed_time:.2f}s答题情况：{self.status}"
        messagebox.showinfo("测试结果", result_text)
        self.destroy()


class ViewWordsPage(tk.Toplevel):
    def __init__(self, master, words, app_instance):
        super().__init__(master)
        self.title("查看单词")

        self.words = words
        self.app_instance = app_instance
        self.current_page = 1
        self.words_per_page = 10  # 修改为每页显示10个单词

        self.create_widgets()
        self.show_page(1)  # 初始显示第一页

    def create_widgets(self):
        self.word_frame = ttk.Frame(self)
        self.word_frame.pack(pady=10)

        self.prev_button = ttk.Button(self, text="上一页", command=self.show_prev_page)
        self.prev_button.pack(side="left", padx=10)

        self.page_label = ttk.Label(self, text="Page 1")
        self.page_label.pack(side="left")

        self.next_button = ttk.Button(self, text="下一页", command=self.show_next_page)
        self.next_button.pack(side="left", padx=10)

        self.view_button = ttk.Button(self, text="刷新并查看", command=self.refresh_words)
        self.view_button.pack(side="left", padx=10)

        self.show_page(1)

    def refresh_words(self):
        self.app_instance.load_words()  # 重新加载单词
        self.app_instance.save_words_to_file()  # 保存单词到文件（以确保格式一致）
        self.show_page(self.current_page)  # 重新显示当前页

    def show_page(self, page):
        self.current_page = page  # 更新当前页码

        # 使用排序后的字典
        sorted_words = sorted(self.words.items())
        start_index = (page - 1) * self.words_per_page
        end_index = start_index + self.words_per_page
        page_words = sorted_words[start_index:end_index]

        for widget in self.word_frame.winfo_children():
            widget.destroy()

        for word, meanings in page_words:
            word_frame = ttk.Frame(self.word_frame)
            word_frame.pack(pady=5, fill="x")

            word_label = ttk.Label(word_frame, text=f"{word}: {', '.join(meanings)}")
            word_label.pack(side="left", padx=5)

            # 创建新的 Frame 用于容纳按钮
            button_frame = ttk.Frame(word_frame)
            button_frame.pack(side="right")

            edit_button = ttk.Button(word_frame, text="修改",
                                     command=lambda w=word: self.edit_word(w))
            edit_button.pack(side="left", padx=5)

            delete_button = ttk.Button(word_frame, text="删除",
                                       command=lambda w=word: self.delete_word(w))
            delete_button.pack(side="left", padx=5)
        # 更新页码信息
        total_pages = (len(sorted_words) + self.words_per_page - 1) // self.words_per_page
        self.page_label.config(text=f"Page {self.current_page} of {total_pages}")


    def show_prev_page(self):
        if self.current_page > 1:
            self.show_page(self.current_page - 1)

    def show_next_page(self):
        total_pages = (len(self.words) + self.words_per_page - 1) // self.words_per_page
        if self.current_page < total_pages:
            self.show_page(self.current_page + 1)

    def edit_word(self, word):
        # 获取原始单词和释义
        original_meanings = ', '.join(self.words[word])

        # 创建新的顶级窗口
        edit_window = tk.Toplevel(self)
        edit_window.title("编辑单词")

        # 添加英文输入框
        english_label = ttk.Label(edit_window, text="英文:")
        english_label.grid(row=0, column=0, padx=5, pady=5)
        english_entry = ttk.Entry(edit_window, width=30)
        english_entry.insert(0, word)
        english_entry.grid(row=0, column=1, padx=5, pady=5)

        # 添加注释输入框
        meanings_label = ttk.Label(edit_window, text="注释:")
        meanings_label.grid(row=1, column=0, padx=5, pady=5)
        meanings_entry = ttk.Entry(edit_window, width=30)
        meanings_entry.insert(0, original_meanings)
        meanings_entry.grid(row=1, column=1, padx=5, pady=5)

        # 定义保存按钮的回调函数
        def save():
            edited_word = english_entry.get()
            edited_meanings = meanings_entry.get()

            # 更新单词和释义
            self.words[edited_word] = edited_meanings.split(',')

            # 保存到文件
            self.app_instance.save_words_to_file()

            # 重新显示当前页
            self.show_page(self.current_page)

            # 关闭编辑窗口
            edit_window.destroy()

        # 添加保存按钮
        save_button = ttk.Button(edit_window, text="保存", command=save)
        save_button.grid(row=2, column=1, padx=5, pady=5)
    def delete_word(self, word):
        confirmation = messagebox.askokcancel("确认删除", f"是否确认删除单词 '{word}'？")
        if confirmation:
            del self.words[word]
            self.app_instance.save_words_to_file()
            messagebox.showinfo("删除成功", f"单词 '{word}' 已成功删除！")
            self.show_page(self.current_page)


class SearchWordsPage(tk.Toplevel):
    def __init__(self, master, words):
        super().__init__(master)
        self.title("搜索单词")

        self.words = words
        self.search_results = {}  # 存储搜索结果
        self.current_page = 1
        self.words_per_page = 10  # 修改为每页显示10个单词

        self.create_widgets()
        self.show_page(1)  # 初始显示第一页

    def create_widgets(self):
        self.search_entry_label = ttk.Label(self, text="输入关键词:")
        self.search_entry_label.pack(pady=10)

        self.search_entry = ttk.Entry(self)
        self.search_entry.pack(pady=10)

        self.search_button = ttk.Button(self, text="搜索", command=self.search_words)
        self.search_button.pack(pady=10)

        self.word_frame = ttk.Frame(self)
        self.word_frame.pack(pady=10)

        self.prev_button = ttk.Button(self, text="上一页", command=self.show_prev_page)
        self.prev_button.pack(side="left", padx=10)

        self.page_label = ttk.Label(self, text="Page 1")
        self.page_label.pack(side="left")

        self.next_button = ttk.Button(self, text="下一页", command=self.show_next_page)
        self.next_button.pack(side="left", padx=10)

        self.show_page(1)

    def search_words(self):
        query = self.search_entry.get().strip().lower()

        # 清空之前的搜索结果
        self.search_results.clear()

        # 进行模糊查询
        for word, meanings in self.words.items():
            if query in word.lower() or any(query in meaning.lower() for meaning in meanings):
                self.search_results[word] = meanings

        # 重新显示第一页
        self.show_page(1)

    def show_page(self, page):
        self.current_page = page

        # 使用排序后的字典
        sorted_words = sorted(self.search_results.items())
        start_index = (page - 1) * self.words_per_page
        end_index = start_index + self.words_per_page
        page_words = sorted_words[start_index:end_index]

        for widget in self.word_frame.winfo_children():
            widget.destroy()

        for word, meanings in page_words:
            word_frame = ttk.Frame(self.word_frame)
            word_frame.pack(pady=5, fill="x")

            word_label = ttk.Label(word_frame, text=f"{word}: {', '.join(meanings)}")
            word_label.pack(side="left", padx=5)

    def show_prev_page(self):
        if self.current_page > 1:
            self.show_page(self.current_page - 1)

    def show_next_page(self):
        total_pages = (len(self.search_results) + self.words_per_page - 1) // self.words_per_page
        if self.current_page < total_pages:
            self.show_page(self.current_page + 1)


if __name__ == "__main__":
    root = tk.Tk()
    app = WordApp(root)
    root.mainloop()
